const mongoose = require('mongoose')
const Joi = require('joi')
// 引入JWT
const jwt = require('jsonwebtoken')
const config = require('../config')

// 定义user结构
const userSchema = new mongoose.Schema({
  // 邮箱
  email: {
    type: 'string',
    required: true,
    unique: true,
    minlength: 6,
    maxlength: 20
  },
  // 用户名
  name: {
    type: 'string',
    require: true,
    minlength: 2,
    maxlength: 20
  },
  // 密码
  password: {
    type: 'string',
    required: true,
    minlength: 2,
    maxlength: 100
  }
})

userSchema.methods.generateToken = function () {
  return jwt.sign(
    {
      _id: this._id
    },
    config.jwtPrivateKey
  )
}

// 创建userModel
const User = mongoose.model('User', userSchema)

function userValidator(user) {
  // 创建内容教研规则对象
  const schema = Joi.object({
    email: Joi.string().email().trim().lowercase().required().messages({
      'any.required': '缺少必选参数email',
      'string.email': 'email格式错误'
    }),
    name: Joi.string().min(2).max(20).messages({
      'string.base': 'name必须为string',
      'string.max': 'name最多为20个字符',
      'string.min': 'name最少为2个字符',
      'any.required': '缺少必选参数name'
    }),
    // password: Joi.string().min(2).max(10).required()
    password: Joi.string()
      .pattern(/^[a-zA-Z0-9]{3,12}$/)
      .required()
      .messages({
        'any.pattern.base': '密码不符合规则',
        'any.required': '缺少必选参数password'
      }),
      _id: Joi.string()
  })

  return schema.validate(user)
}

module.exports = {
  // 导出的model
  User,
  // 导出的校验函数
  userValidator
}
